using System.Collections.Generic;
using LitJson;
namespace CGF
{
    public partial class PanelSalesIncomeDetail : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private string year, month, day;

        public static void Open(string year, string month, string day)
        {
            UIManagerComponent.instance.OpenUI<PanelSalesIncomeDetail>(UILayer.Normal, RootComponent.instance, false).SetInfo(year, month, day);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelSalesIncomeDetail>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelSalesIncomeDetail", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(Close);

            Curr.text = I18N.Currency;
            TitleSub.text = "";

            if (year != null)
            {
                SetInfo(year, month, day);
            }
        }

        private void SetInfo(string year, string month, string day)
        {
            this.year = year;
            this.month = month;
            this.day = day;
            if (!Curr) return;

            string dateStr = $"{month}/{day}";
            if (CGFConfig.Instance.ReleaseArea != EArea.China)
            {
                dateStr = $"{day}/{month}";
            }
            Title.text = I18N_title.Replace("{date}", dateStr);
            ReqData();
        }

        private async void ReqData()
        {
            string api = $"/v1/earnings/commission/detail?date={year}-{month}-{day}";
            var res = await Network.Get(api);
            List<JsonData> list = new List<JsonData>();
            JsonData data = res.jsonData["data"];
            for (int i = 0; i < data.Count; i++)
            {
                JsonData cell = data[i];
                string sourceUserId = cell["source_user_id"].ToString();
                int type = (int)cell["type"];
                int total_income = (int)cell["total_income"];
                if (type == 1)
                {
                    //静态收益
                    cell["static"] = total_income;
                    cell["dynamic"] = 0;
                }
                else
                {
                    //动态收益
                    cell["static"] = 0;
                    cell["dynamic"] = total_income;
                }
                bool isExist = false;
                for (int j = 0; j < list.Count; j++)
                {
                    if (list[j]["source_user_id"].ToString() == sourceUserId)
                    {
                        //下级id已在列表里时，直接附加数据进去，不在插入新Cell
                        if (type == 1)
                        {
                            //静态收益
                            list[j]["static"] = (int)list[j]["static"] + total_income;
                        }
                        else
                        {
                            //动态收益
                            list[j]["dynamic"] = (int)list[j]["dynamic"] + total_income;
                        }
                        isExist = true;
                        break;
                    }
                }
                if (isExist) continue;
                list.Add(cell);
            }
            //传给Table渲染
            Table.Column[] columns =
            {
                (cell, data) => data["source_user_id"].ToString(),
                (cell, data) => $"<color={Config.NumColor}>{I18N.Currency}<b>{StringHelper.Format2Decimal((int)data["static"] * 0.01f)}</b></color>",
                (cell, data) => $"<color={Config.NumColor}>{I18N.Currency}<b>{StringHelper.Format2Decimal((int)data["dynamic"] * 0.01f)}</b></color>",
                (cell, data) => $"<color={Config.NumColor}>{I18N.Currency}<b>{StringHelper.Format2Decimal(((int)data["static"] + (int)data["dynamic"]) * 0.01f)}</b></color>",
            };
            Table.GetComponent<Table>().SetData(list, columns);
            int totalAmount = 0;
            for (int i = 0; i < list.Count; i++)
            {
                totalAmount += (int)list[i]["static"];
                totalAmount += (int)list[i]["dynamic"];
            }
            TitleSub.text = I18N_title_sub.Replace("{amount}", $"{I18N.Currency} {StringHelper.Format2Decimal(totalAmount * 0.01f)}");
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
